package com.jiuyin.dianjing.ui.activity.community;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.google.gson.JsonObject;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.api.base.DefaultApiResult;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.event.RefreshEvent;
import com.jiuyin.dianjing.model.FileModel;
import com.jiuyin.dianjing.permission.XPermission;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.ui.fragment.community.PostFragment;
import com.jiuyin.dianjing.util.FileUtils;
import com.jiuyin.dianjing.util.IMEUtil;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.ToastUtil;
import com.rain.library.bean.Photo;
import com.rain.library.controller.PhotoPickConfig;
import com.rain.library.glide.GlideImageLoader;
import com.rain.library.impl.PhotoSelectCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_CONTENT;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_FORK_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_GAME_TAG;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_GENRE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_GENRE_TAG;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_PHOTO;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TITLE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.constant.AppConstant.FOLDER_NAME;
import static com.jiuyin.dianjing.constant.AppConstant.MAX_PHOTO_SIZE;

public class CreatePostActivity extends BaseActivity {
    public static final int RC_CHOOSE_TAG = 3;
    private static final int RC_CHOOSE_PHOTO = 1;
    private static final int RC_PHOTO_PREVIEW = 2;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.pic)
    BGASortableNinePhotoLayout mPhotosSnpl;
    @BindView(R.id.tv_tag)
    TextView tvTag;
    @BindView(R.id.bt_publish)
    Button btPublish;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rg_genre)
    RadioGroup rgGenre;

    //帖子区域类型（0普通 1 高校电竞社 ）
    private String mGenre;
    private String mGenreTag;
    private String mGameTag;
    private StringBuilder photoBuilder;
    private String mForkId;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_create_post;
    }

    @Override
    protected void initData() {
        mGenre = getIntent().getStringExtra("genre");
        mForkId = getIntent().getStringExtra("forkId");
        doPermission();
    }

    /**
     * 动态请求照相和存储权限
     */
    private void doPermission() {
        XPermission.requestPermissions(this, 101, new String[]{Manifest.permission
                .WRITE_EXTERNAL_STORAGE}, new XPermission.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {

            }

            @Override
            public void onPermissionDenied() {
                XPermission.showTipsDialog(CreatePostActivity.this);
            }
        });
    }

    @Override
    protected void initView() {
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(v -> {
            onBackPressed();
        });
        tvTitle.setText("发表帖子");
        tvTag.setOnClickListener(v -> {
            Intent intent = new Intent(CreatePostActivity.this, TagActivity.class);
            startActivityForResult(intent, RC_CHOOSE_TAG);
        });
        btPublish.setOnClickListener(v -> {
            if (validateInput()) {
                uploadFiles();
            }
        });
        mPhotosSnpl.setDelegate(new BGASortableNinePhotoLayout.Delegate() {
            @Override
            public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
                choicePhotoWrapper();
            }

            @Override
            public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
                mPhotosSnpl.removeItem(position);
            }

            @Override
            public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
                Intent photoPickerPreviewIntent = new BGAPhotoPickerPreviewActivity.IntentBuilder(CreatePostActivity.this)
                        .previewPhotos(models) // 当前预览的图片路径集合
                        .selectedPhotos(models) // 当前已选中的图片路径集合
                        .maxChooseCount(mPhotosSnpl.getMaxItemCount()) // 图片选择张数的最大值
                        .currentPosition(position) // 当前预览图片的索引
                        .isFromTakePhoto(false) // 是否是拍完照后跳转过来
                        .build();
                startActivityForResult(photoPickerPreviewIntent, RC_PHOTO_PREVIEW);
            }

            @Override
            public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {
                Toast.makeText(CreatePostActivity.this, "排序发生变化", Toast.LENGTH_SHORT).show();
            }

            private void choicePhotoWrapper() {
                new PhotoPickConfig
                        .Builder(CreatePostActivity.this)
                        .imageLoader(new GlideImageLoader())
                        .pickMode(PhotoPickConfig.MODE_PICK_MORE)
                        .maxPickSize(MAX_PHOTO_SIZE - mPhotosSnpl.getItemCount())
                        .showCamera(true)
                        .setCallback(new PhotoSelectCallback() {
                            @Override
                            public void moreSelect(ArrayList<Photo> photos) {
                                selectPhoto(photos);
                            }

                            @Override
                            public void singleSelect(ArrayList<Photo> photos) {
                                selectPhoto(photos);
                            }

                            private void selectPhoto(ArrayList<Photo> photos) {
                                int size = photos.size();
                                ArrayList<String> list = new ArrayList<>(size);
                                if (PhotoPickConfig.DEFAULT_START_COMPRESSION) {
                                    for (int i = 0; i < size; i++) {
                                        list.add(photos.get(i).getCompressionImagePath());
                                    }
                                } else {
                                    for (int i = 0; i < size; i++) {
                                        if (!TextUtils.isEmpty(photos.get(i).getCameraImagePath())){
                                            list.add(photos.get(i).getCameraImagePath());
                                        }else {
                                            list.add(photos.get(i).getOriginalImagePath());
                                        }
                                    }
                                }
                                mPhotosSnpl.addMoreData(list);
                            }
                        }).build();
            }
        });
    }

    private boolean validateInput() {
        boolean ok = true;
        if (etTitle.getText().toString().trim().length() == 0) {
            ok = false;
            ToastUtil.showShort("请填写标题");
        } else if (etContent.getText().toString().trim().length() == 0) {
            ok = false;
            ToastUtil.showShort("请填写内容");
        }
        return ok;
    }


    void uploadFiles() {
        ArrayList<String> list = mPhotosSnpl.getData();
        if (null == list || 0 == list.size()) {
            ToastUtil.showShort(R.string.photo_not_select);
            return;
        }
        btPublish.setEnabled(false);
        photoBuilder = new StringBuilder();
        final List<FileModel> files = new ArrayList<>();
        for (String filePath : mPhotosSnpl.getData()) {
            String fileName = FileUtils.generateFileName(filePath);
            fileName = FOLDER_NAME + fileName;
            photoBuilder.append("http://jiuyinesports.com/").append(fileName).append(",");
            FileModel fileModel = new FileModel(fileName, filePath);
            files.add(fileModel);
        }
        if (photoBuilder.length() > 0) {
            photoBuilder.deleteCharAt(photoBuilder.length() - 1);
        }
        showLoading();

        //上传图片到阿里云OSS
        OSSCompletedCallback<PutObjectRequest, PutObjectResult> userCallback = new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            private int time = 0;

            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                int size = files.size();
                LogUtil.log("UploadSuccess");
                String fileName = request.getObjectKey();
                for (FileModel file : files) {
                    if (file.fileName.equals(fileName)) {
                        time++;
                        file.success = true;
                        break;
                    }
                }
                if (time == size) {
                    dismissLoading();
                    publish();
                }
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                if (clientException != null) {
                    ToastUtil.showShort("客户端异常:图片上传失败");
                    LogUtil.log(clientException.getMessage());
                }
                if (serviceException != null) {
                    ToastUtil.showShort("服务端异常:图片上传失败");
                    LogUtil.log(serviceException.getMessage());
                }
                btPublish.setEnabled(true);
                dismissLoading();
            }
        };
        HelperApplication.ossService.asyncPutImages(files, userCallback, null);
    }

    private void publish() {
        HashMap<String, Object> params = new HashMap<>();
        params.put(KEY_TOKEN, HelperApplication.getToken());
        params.put(KEY_TITLE, etTitle.getText().toString().trim());
        params.put(KEY_CONTENT, etContent.getText().toString().trim());
        params.put(KEY_PHOTO, photoBuilder.toString());//图片地址（用逗号拼接）
        params.put(KEY_GENRE_TAG, mGenreTag);//期望标签 传入字面值非id
        params.put(KEY_GAME_TAG, mGameTag);//游戏标签 传入字面值非id
        params.put(KEY_GENRE, mGenre);//帖子区域类型（0普通 1 高校电竞社 ）
        if (!TextUtils.isEmpty(mForkId)) {
            params.put(KEY_FORK_ID, mForkId);//帖子区域类型（0普通 1 高校电竞社 ）
        }
        JSONObject jsonObject = new JSONObject(params);
        ApiResultCallback requestCallback = new DefaultApiResult() {
            @Override
            public void onSuccess(JsonObject data) {
                IMEUtil.hideInputMethod(CreatePostActivity.this);
                EventBus.getDefault().post(new RefreshEvent(PostFragment.class.getSimpleName()));
                onBackPressed();
                finish();
            }

            @Override
            public void onFail(String msg) {
                super.onFail(msg);
                btPublish.setEnabled(true);
            }

            @Override
            public void onError(String msg) {
                super.onError(msg);
                btPublish.setEnabled(true);
            }
        };
        ServerApi.post(ApiEnum.APP_PUBLISH_TOPIC.getUrl(), jsonObject, null, progress, null, requestCallback);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RC_CHOOSE_PHOTO:
                    mPhotosSnpl.addMoreData(BGAPhotoPickerActivity.getSelectedPhotos(data));
                    break;
                case RC_PHOTO_PREVIEW:
                    mPhotosSnpl.setData(BGAPhotoPickerPreviewActivity.getSelectedPhotos(data));
                    break;
                case RC_CHOOSE_TAG:
                    mGenreTag = data.getStringExtra(TagActivity.KEY_DESIRE_TAG);
                    mGameTag = data.getStringExtra(TagActivity.KEY_GAME_TAG);
                    if (!TextUtils.isEmpty(mGenreTag)) {
                        StringBuilder temp = new StringBuilder(mGenreTag);
                        if (!TextUtils.isEmpty(mGameTag)) {
                            temp.append(" ").append(mGameTag);
                        }
                        tvTag.setText(temp.toString());
                    } else if (!TextUtils.isEmpty(mGameTag))
                        tvTag.setText(mGameTag);
                    break;
            }
        }
    }
}